import {
	BitSet,
	BitClr,
	Set2Byte,
	DataGet,
	ab2hex,
	hexCharCodeToStr,
	arrayToBuffer,
	Parse,
	Set3Byte,
	bitToStr,
	Set1Byte,
	feedback,
	Set4Byte,
	Get2Byte,
	Get4Byte,
	Get3Byte,
	getByBite,
	hexToSignedDecimal,uploadEquipCommlog,
} from "@/utils/index.js";
import {
	serviceId,
	characteristicId2,
} from "@/utils/service.js";

import {
	READ_AND_WRITE_STATUS,
} from "@/common/config.js";
export default {
	data() {
		return {
			startTime: null, //开始时间戳
		}
	},
	methods: {
		isRead(addr) {
			let that = this;
			uni.showModal({
				title: '提示',
				content: '确定要查询吗？',
				success(res) {
					if (res.confirm) {
						that.doRead(addr);
					}
				}
			})
		},
		// 一键诊断 读取设备信息
		async doRead(addr) {
			let that = this;
			that.$Toast.loading('查询中~');
			this.startTime = new Date().getTime();
			
			let datas = DataGet(this.command, 0, addr ? addr : 0, 0, 0, null);
			let buffer = arrayToBuffer(datas);
			
			let requestHex = ab2hex(buffer);
			
			let {
				deviceId,
			} = this.deviceInfo;
			uni.writeBLECharacteristicValue({
				deviceId,
				serviceId,
				characteristicId: characteristicId2,
				// 这里的value是ArrayBuffer类型
				value: buffer,
				success(res) {
					setTimeout(()=>{
						that.doCharData(addr);
					},300)
					
					uploadEquipCommlog(requestHex, '', READ_AND_WRITE_STATUS[1], 1, that.startTime,
						that.deviceInfo,that.dgMessage);
				},
				fail(err) {
					console.log(err)
					that.$Toast.none(`${that.dgMessage}检测失败!`);
					uploadEquipCommlog(requestHex, '', READ_AND_WRITE_STATUS[1], 0,that.startTime,
						that.deviceInfo,that.dgMessage);
				}
			})
		},
		// 读取数据
		doCharData(addr) {
			let {
				deviceId
			} = this.deviceInfo;
			let that = this;
			this.startTime = new Date().getTime();
			
			// 读取低功耗蓝牙设备的特征值的二进制数据值
			uni.readBLECharacteristicValue({
				deviceId,
				serviceId,
				characteristicId: characteristicId2,
				success(res) {
					uni.onBLECharacteristicValueChange(function(res) {
						uni.hideLoading();
						// 解析数据
						let buffer = res.value;
						const uint8Array = new Uint8Array(res.value);

						const newArray = Array.from(uint8Array);

						let databuff = Parse(newArray);
						
						uploadEquipCommlog('', ab2hex(res.value), READ_AND_WRITE_STATUS[0], 1,that.startTime,
						that.deviceInfo,that.dgMessage);
						
						if (databuff && (databuff.dataUnit || databuff.dataUnit == 0)) {
							switch (databuff.dataUnit) {
								//数据单元 0：主控单元;1：检测单元;2：仓控单元;3：柜控电源单元;4：整流电源单元;5：电池单元;6：消防单元;7：充电电源
								case 0:
									if (databuff.databuff && databuff.databuff.length == 27) {
										that.masterControl.param1 = databuff.databuff[0];
										that.masterControl.param2 = databuff.databuff[1];
										that.masterControl.param3 = databuff.databuff[2];
										that.masterControl.param4 = databuff.databuff[3];

										let str5 = ab2hex(res.value.slice(11, 31));
										that.masterControl.param5 = hexCharCodeToStr(str5);

										that.masterControl.param6 = databuff.databuff[24];
										that.masterControl.param7 = databuff.databuff[25];
										that.masterControl.param8 = databuff.databuff[26];
									}
									break;
								case 1:
									// 检测单元
									if (databuff.databuff && databuff.databuff.length == 17) {
										let param1 = Get2Byte(databuff.databuff.slice(0, 2));
										that.unitInfo.param1 = (param1 / 10).toFixed(1);

										let param2 = Get2Byte(databuff.databuff.slice(2, 4));
										that.unitInfo.param2 = (param2 / 100).toFixed(2);

										let param3 = Get4Byte(databuff.databuff.slice(4, 8));
										that.unitInfo.param3 = (param3 / 100).toFixed(2);

										let param4 = Get2Byte(databuff.databuff.slice(8, 10));
										that.unitInfo.param4 = param4;

										let param5 = Get2Byte(databuff.databuff.slice(10, 12));
										that.unitInfo.param5 = param5;
										let param6 = databuff.databuff[12];
										that.unitInfo.param6 = param6;
										let param7 = databuff.databuff.slice(13, 16);
										// 3字节按位取出
										let arr7 = [...getByBite(param7[0]), ...getByBite(param7[1]),
											...
											getByBite(param7[2])
										];
										arr7.forEach((item, index) => {
											if (index < 18) {
												that.unitInfo[`param${7+index}`] = item;
											} else {
												that.unitInfo[`param${7+index}`] = arr7[index +
													1];
											}
										});

										let param8 = [...getByBite(databuff.databuff[16])];
										that.unitInfo.param30 = parseInt(param8.slice(0, 2).reverse()
											.join(''), 2);
										that.unitInfo.param31 = param8[2];
										that.unitInfo.param32 = param8[3];
										that.unitInfo.param33 = param8[4];
										that.unitInfo.param34 = param8[5];
									}
									break;
								case 2:
									if (databuff.databuff && databuff.databuff.length == 7) {
										// 1.2 仓状态
										that.binStatus.param1 = databuff.databuff[0];
										that.binStatus.param2 = databuff.databuff[1];
										// 仓温度
										that.binStatus.param3 = Get2Byte(databuff.databuff.slice(2, 4));
										that.binStatus.param4 = databuff.databuff[4];
										// 开关量
										let param1 = databuff.databuff.slice(5, 7);
										let arr1 = [...getByBite(param1[0]), ...getByBite(param1[1])];
										arr1.forEach((item, index) => {
											if (index < 14) {
												that.binStatus[`param${5+index}`] = item;
											}
										})
									}
									break;
								case 3:
									// 检测单元
									if (databuff.databuff && databuff.databuff.length == 8) {
										let param1 = Get2Byte(databuff.databuff.slice(0, 2));
										that.cabinetInfo.param1 = (param1 / 100)
											.toFixed(2);

										let param2 = Get2Byte(databuff.databuff.slice(2, 4));
										that.cabinetInfo.param2 = (param2 / 100)
											.toFixed(2);

										that.cabinetInfo.param3 = Get2Byte(databuff.databuff.slice(4,
											6));

										let param4 = databuff.databuff.slice(6, 8);
										// 2字节按位取出
										let arr4 = [...getByBite(param4[0]), ...getByBite(param4[1])];
										arr4.forEach((item, index) => {
											if (index < 9) {
												that.cabinetInfo[`param${4+index}`] = item;
											}
										});
									}
									break;
								case 4:
									if (databuff.databuff && databuff.databuff.length == 10) {
										let param1 = Get2Byte(databuff.databuff.slice(0, 2));
										that.powerInfo.param1 = (param1 / 100)
											.toFixed(2);

										let param2 = Get2Byte(databuff.databuff.slice(2, 4));
										that.powerInfo.param2 = (param2 / 100)
											.toFixed(
												2);

										that.powerInfo.param3 = Get2Byte(databuff.databuff.slice(4, 6));
										that.powerInfo.param4 = Get2Byte(databuff.databuff.slice(6, 8));

										let param4 = databuff.databuff.slice(8, 10);
										// 2字节按位取出
										let arr4 = [...getByBite(param4[0]), ...getByBite(param4[1])];
										arr4.forEach((item, index) => {
											if (index < 12) {
												that.powerInfo[`param${5+index}`] = item;
											}
										});
									}
									break;
								case 5:
									if (databuff.databuff && databuff.databuff.length == 91) {
										// 7字节按位取出
										let param1 = databuff.databuff.slice(0, 7);
										let arr1 = [...getByBite(param1[0]), ...getByBite(param1[1]),
											...
											getByBite(param1[2]), ...getByBite(param1[3]), ...
											getByBite(param1[4]), ...getByBite(param1[5]), ...
											getByBite(param1[6])
										];
										// param1-51
										arr1.forEach((item, index) => { //Bit0:保留位
											if (index > 0 && index < 52) { //53-56位保留
												that.batteryInfo[`param${index}`] = item;
											}
										});
										// 5字节按位取出
										let param2 = databuff.databuff.slice(7, 12);
										let arr2 = [...getByBite(param2[0]), ...getByBite(param2[1]),
											...
											getByBite(param2[2]), ...getByBite(param2[3]), ...
											getByBite(param2[4])
										];
										arr2.forEach((item, index) => { //52-91
											that.batteryInfo[`param${52+index}`] = item;
										});

										// SN 32字节 第29-32字节预留 小端模式传输
										let param3 = databuff.databuff.slice(12, 40);
										const dataArray = param3.map(byte => String.fromCharCode(byte));
										// 连接字符以生成字符串
										that.batteryInfo.param92 = dataArray.join('');

										// 电池包实际总电压
										let param4 = Get2Byte(databuff.databuff.slice(44, 46));
										that.batteryInfo.param93 = (param4 / 100)
											.toFixed(
												2);

										// 电芯数量
										let param5 = Get2Byte(databuff.databuff.slice(46, 48));
										that.batteryInfo.param94 = param5;
										// SOC
										let param6 = Get2Byte(databuff.databuff.slice(48, 50));
										that.batteryInfo.param95 = param6;
										// 剩余容量
										let param7 = Get2Byte(databuff.databuff.slice(50, 52));
										that.batteryInfo.param96 = (param7 / 100)
											.toFixed(2);
										// SOH
										let param8 = Get2Byte(databuff.databuff.slice(52, 54));
										that.batteryInfo.param97 = param8;
										// 充电电流
										let param9 = Get2Byte(databuff.databuff.slice(54, 56));
										that.batteryInfo.param98 = (param9 / 100)
											.toFixed(2);
										// 环境温度
										let param10 = Get2Byte(databuff.databuff.slice(56, 58));
										that.batteryInfo.param99 = param10;
										// 电芯最低温度
										let param11 = Get2Byte(databuff.databuff.slice(58, 60));
										that.batteryInfo.param100 = param11;
										// 板卡温度
										let param12 = Get2Byte(databuff.databuff.slice(60, 62));
										that.batteryInfo.param101 = param12;
										// 电芯最高电压
										let param13 = Get2Byte(databuff.databuff.slice(62, 64));
										that.batteryInfo.param102 = (param13 / 1000)
											.toFixed(3);
										// 电芯最低电压
										let param14 = Get2Byte(databuff.databuff.slice(64, 66));
										that.batteryInfo.param103 = (param14 / 1000)
											.toFixed(3);
										// 电芯最高温度
										that.batteryInfo.param104 = Get2Byte(databuff.databuff.slice(66,
											68));
										// 充电电流请求值
										let param15 = Get2Byte(databuff.databuff.slice(68, 70));
										that.batteryInfo.param105 = (param15 / 100)
											.toFixed(2);
										// 充电电压请求值
										let param16 = Get2Byte(databuff.databuff.slice(70, 72));
										that.batteryInfo.param106 = (param16 / 100)
											.toFixed(2);
										// BMS充电标志位
										that.batteryInfo.param107 = Get2Byte(databuff.databuff.slice(72,
											74));
										// 快充充电电流请求值
										let param17 = Get2Byte(databuff.databuff.slice(74, 76));
										that.batteryInfo.param108 = (param17 / 100)
											.toFixed(2);
										// 快充充电电压请求值
										let param18 = Get2Byte(databuff.databuff.slice(76, 78));
										that.batteryInfo.param109 = (param18 / 100)
											.toFixed(2);
										// BMS快充充电标志位
										that.batteryInfo.param110 = Get2Byte(databuff.databuff.slice(78,
											80));

										// MOS状态
										let param19 = getByBite(databuff.databuff[80]);
										that.batteryInfo.param111 = param19[0];
										that.batteryInfo.param112 = param19[1];
										// 电池版本
										that.batteryInfo.param113 = databuff.databuff[81];
										// 电池容量校准标志位
										that.batteryInfo.param114 = databuff.databuff[82];
										// 放电电流请求值
										let param20 = Get2Byte(databuff.databuff.slice(83, 85));
										that.batteryInfo.param115 = (param20 / 100)
											.toFixed(2);

										// 电池状态
										that.batteryInfo.param116 = databuff.databuff[85];
										// BMS控制状态
										that.batteryInfo.param117 = databuff.databuff[86];
										// 电池开关量
										let param21 = databuff.databuff.slice(87, 95);
										let param22 = databuff.databuff.slice(95, 103);
										let param23 = databuff.databuff.slice(103, 111);
										let param24 = databuff.databuff.slice(111, 119);
										let arr3 = [...getByBite(param21[0]), ...getByBite(param22[1]),
											...
											getByBite(param23[2]), ...getByBite(param24[3])
										];

										arr3.forEach((item, index) => {
											if (index < 32) { //预留位
												that.batteryInfo[`param${118+index}`] = item;
											}
										});
									}
									break;
								case 7:
									if (databuff.databuff && databuff.databuff.length == 14) {
										// 电源侧电压
										let param1 = Get2Byte(databuff.databuff.slice(0, 2));
										that.chargeInfo.param1 = (param1 / 100)
											.toFixed(2);

										// 电源侧电流
										let param2 = hexToSignedDecimal(ab2hex(buffer.slice(9, 11)));
										that.chargeInfo.param2 = (param2 / 100)
											.toFixed(2);

										// DC/DC温度
										that.chargeInfo.param3 = databuff.databuff[4];

										// 开关量1
										let param3 = Get2Byte(databuff.databuff.slice(5, 7));
										let arr3 = [...getByBite(param3[0]), ...getByBite(param3[1])];
										arr3.forEach((item, index) => {
											if (index < 10) {
												that.chargeInfo[`param${4+index}`] = item;
											}
										});
										that.chargeInfo.param14 = Get3Byte(arr3.slice(10, 13));
											
										that.chargeInfo.param15 = arr3[13];

										// 运行状态
										that.chargeInfo.param16 = databuff.databuff[7];

										// 开关量2
										// 2字节按位取出
										let param4 = databuff.databuff.slice(8, 10);
										let arr4 = [...getByBite(param4[0]), ...getByBite(param4[1])];
										arr4.forEach((item, index) => {
											that.chargeInfo[`param${17+index}`] = item;
										});

										// 开关量3
										let arr5 = [...getByBite(databuff.databuff[10])];
										arr5.forEach((item, index) => {
											if (index < 7) {
												that.chargeInfo[`param${33+index}`] = item;
											}
										});

										// 电池在位电压
										that.chargeInfo.param40 = databuff.databuff[11];
										// 电池充电时长
										that.chargeInfo.param41 = Get2Byte(databuff.databuff.slice(12,
											14));
									}
									break;
							}
						}
					})
				},
				fail(fal) {
					console.log("读取数据数据失败", fal)
					that.$Toast.none(`${that.dgMessage}检测失败!`);
					uploadEquipCommlog('', fal.errCode, READ_AND_WRITE_STATUS[0], 0,that.startTime,
						that.deviceInfo,that.dgMessage);
				}
			})
		},
		// 仓状态详情
		binPopup(index) {
			this.$refs.binpopup.open('center');
			this.currentIndex = index + 1;
			this.currentCollapse = 1;
			this.command = 2;
			this.dgMessage = `${this.currentIndex}号仓`;
			for (let key of Object.keys(this.binStatus)) {
				this.binStatus[key] = "";
			}
			// 读取仓状态
			this.doRead(index);
		},
		batteryPopup(index) {
			this.$refs.batterypopup.open('center');
			this.currentIndex = index + 1;
			this.command = 5;
			this.dgMessage = `电池${this.currentIndex}`;

			for (let key of Object.keys(this.batteryInfo)) {
				this.batteryInfo[key] = "";
			}
			// 读取仓状态
			this.doRead(index);
		},
		chargePopup(index) {
			this.$refs.chargepopup.open('center');
			this.currentIndex = index + 1;
			this.command = 7;
			this.dgMessage = `充电电源${this.currentIndex}`;

			for (let key of Object.keys(this.chargeInfo)) {
				this.chargeInfo[key] = "";
			}
			// 读取仓状态
			this.doRead(index);
		},
		cabinetPopup(index) {
			this.$refs.cabinetpopup.open('center');
			this.currentIndex = index + 1;
			this.command = 3;
			this.dgMessage = `柜控电源${this.currentIndex}`;

			for (let key of Object.keys(this.cabinetInfo)) {
				this.cabinetInfo[key] = "";
			}
			// 读取仓状态
			this.doRead(index);
		},
		unitPopup(index) {
			this.$refs.unitpopup.open('center');
			this.currentIndex = index + 1;
			this.command = 1;
			this.dgMessage = `检测单元${this.currentIndex}`;

			for (let key of Object.keys(this.unitInfo)) {
				this.unitInfo[key] = "";
			}
			// 读取仓状态
			this.doRead(index);
		},
		powerPopup(index) {
			this.$refs.powerpopup.open('center');
			this.currentIndex = index + 1;
			this.command = 4;
			this.dgMessage = `整流电源${this.currentIndex}`;

			for (let key of Object.keys(this.powerInfo)) {
				this.powerInfo[key] = "";
			}
			// 读取仓状态
			this.doRead(index);
		},
		// 数据单元
		detailCommand() {
			// currentCollapse:0,主控单元;1,仓状态;2,检测单元状态信息;3,柜控电源;4,整流电源;5,充电电源;6,电池
			switch (this.command) {
				case 0:
					this.dgMessage = "主控单元";
					break;
				case 1:
					this.dgMessage = "检测单元";
					break;
				case 3:
					this.dgMessage = "柜控电源";
					break;
				case 4:
					this.dgMessage = "整流电源";
					break;
				case 5:
					this.dgMessage = "电池单元";
					break;
				case 7:
					this.dgMessage = "充电电源";
					break;
			}
		},
		detailData() {
			switch (this.type) {
				case "0":
					this.paramTitle = "主控单元";
					this.command = 0;
					break;
				case "1":
					this.paramTitle = "仓控单元";
					this.command = 2;
					if (this.index || this.index == 0) {
						this.paramTitle += `(${this.index+1}号仓)`
					}
					break;
				case "2":
					this.paramTitle = "检测单元";
					if (this.index || this.index == 0) {
						this.paramTitle += `${this.index+1}`
					}
					this.command = 1;
					break;
				case "3":
					this.paramTitle = "柜控电源单元";
					if (this.index || this.index == 0) {
						this.paramTitle += `${this.index+1}`
					}
					this.command = 3;
					break;
				case "4":
					this.paramTitle = "整流电源单元";
					if (this.index || this.index == 0) {
						this.paramTitle += `${this.index+1}`
					}
					this.command = 4;
					break;
				case "5":
					this.paramTitle = "充电电源";
					if (this.index || this.index == 0) {
						this.paramTitle += `${this.index+1}`
					}
					this.command = 7;
					break;
				case "6":
					this.paramTitle = "电池单元";
					if (this.index || this.index == 0) {
						this.paramTitle += `${this.index+1}`
					}
					this.command = 5;
					break;
			}
			this.dgMessage = this.paramTitle;
		},
	},
}